package com.glwan.fixedassetapp.utils;

import android.util.Log;

import com.glwan.fixedassetapp.model.Asset;
import com.glwan.fixedassetapp.model.kingdee.AddAsset;
import com.glwan.fixedassetapp.model.kingdee.FaCard;
import com.glwan.fixedassetapp.model.kingdee.KingDeeRepoRet;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kingdee.bos.webapi.entity.DataCenter;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;

import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KingDeeUtil {

    private static final String TAG = "KingDeeUtil";

    //第三方系统登录授权的应用ID
    private final static String APPID = "286877_0Z5C08sp6qg8wYWt4e5rR8XKRq177pso";

    //密钥 bb14a755e2f948948cad33ec008e705f

    //第三方系统登录授权的账套ID
    public final static String ACCTID = "66b34a78e4cbb2";

    //账套语系，默认2052
    private final static Integer LCID = 2052;

    //允许的最大连接延时，单位为秒
    private final static int CONNNECTIEMOUT = 120;

    //允许的最大读取延时，单位为秒
    private final static int REQUESTTIMEOUT = 120;

    private static IdentifyInfo identifyInfo;

    private static Map<String, String> assetTypeNumAndNameMap = new HashMap<>();

    private static Map<String, String> assetTypeIdAndNameMap = new HashMap<>();

    private static Map<String, String> assetPositionCodeMap = new HashMap<>();

    private static Map<String, String> assetPositionNameMap = new HashMap<>();

    private static Map<String, String> assetCodeAndNameMap = new HashMap<>();

    private static Map<String, String> assetSupplierNameMap = new HashMap<>();
    private static Map<String, String> assetSupplierCodeMap = new HashMap<>();

    private static Map<String, String> assetUnitCodeMap = new HashMap<>();

    private static Map<String, String> assetUnitNameMap = new HashMap<>();

    private static Map<String, String> assetStatusCodeMap = new HashMap<>();

    private static Map<String, String> assetStatusNameMap = new HashMap<>();


    private static Map<String, String> assetInventSchemeBillNoMap = new HashMap<>();

    private static Map<String, String> assetDataCenterMap = new HashMap<>();

    private static Long notCounted = 0L;
    private static Long counted = 0L;
    private static Long errorCounted = 0L;


    public static IdentifyInfo getIdentifyInfo() {
        if (identifyInfo == null) {
            identifyInfo = new IdentifyInfo();
            identifyInfo.setAppId(APPID);
            identifyInfo.setdCID(ACCTID);
            identifyInfo.setlCID(LCID);
            identifyInfo.setConnectTimeout(CONNNECTIEMOUT);
            identifyInfo.setRequestTimeout(REQUESTTIMEOUT);
        }
        return identifyInfo;
    }

    //资产类别
    public static void getAssetType() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        JsonObject data = new JsonObject();
        data.addProperty("FormId", "FA_ASSETTYPE");
        data.addProperty("FieldKeys", "FID,FNumber,FName");
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            for (List<Object> innerList : lists) {
                for (int i = 0; i < innerList.size(); i++) {
                    if (innerList.get(0).toString().contains("IsSuccess=false")) {
                        Log.e(TAG, "getAssetType: 获取资产类别失败: " + innerList.get(0).toString());
                        break;
                    }
                    assetTypeNumAndNameMap.put(innerList.get(1).toString(), innerList.get(2).toString());
                    assetTypeIdAndNameMap.put(innerList.get(0).toString(), innerList.get(2).toString());
                }
            }
            Log.i(TAG, "getAssetType assetTypeNumAndNameMap: " + new Gson().toJson(assetTypeNumAndNameMap));
            Log.i(TAG, "getAssetType assetTypeIdAndNameMap: " + new Gson().toJson(assetTypeIdAndNameMap));
        } catch (Exception e) {
            Log.e(TAG, "getAssetType: 获取资产类别异常", e);
        }
    }

    //资产位置
    public static Map<String, String> getAssetPosition() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        JsonObject data = new JsonObject();
        data.addProperty("FormId", "FA_POSITION");
        data.addProperty("FieldKeys", "FID,FNumber,FName");
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            for (List<Object> innerList : lists) {
                for (int i = 0; i < innerList.size(); i++) {
                    if (innerList.get(0).toString().contains("IsSuccess=false")) {
                        Log.e(TAG, "getAssetPosition: 获取资产位置失败: " + innerList.get(0).toString());
                        break;
                    }
                    assetPositionCodeMap.put(innerList.get(0).toString(), innerList.get(1).toString());
                    assetPositionNameMap.put(innerList.get(0).toString(), innerList.get(2).toString());
                }
            }
            return assetPositionNameMap;
        } catch (Exception e) {
            Log.e(TAG, "getAssetPosition: 获取资产位置异常", e);
            return assetPositionNameMap;
        }
    }

    //资产名称
    public static void getAssetName() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        JsonObject data = new JsonObject();
        data.addProperty("FormId", "FA_CARD");
        data.addProperty("FieldKeys", "FAssetNO,FName");
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            for (List<Object> innerList : lists) {
                for (int i = 0; i < innerList.size(); i++) {
                    if (innerList.get(0).toString().contains("IsSuccess=false")) {
                        Log.e(TAG, "getAssetName: 获取资源名称失败: " + innerList.get(0).toString());
                        break;
                    }
                    assetCodeAndNameMap.put(innerList.get(0).toString(), innerList.get(1).toString());
//                    if(innerList.get(0).toString().equals(number)){
//                        assetCodeAndNameMap.put(innerList.get(0).toString(), innerList.get(1).toString());
//                        break;
//                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getAssetName:获取资源名称异常", e);
        }
    }

    //供应商
    public static void getAssetSupplier() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        JsonObject data = new JsonObject();
        data.addProperty("FormId", "BD_Supplier");
        data.addProperty("FieldKeys", "FSupplierId,FNumber,FName");
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            for (List<Object> innerList : lists) {
                for (int i = 0; i < innerList.size(); i++) {
                    if (innerList.get(0).toString().contains("IsSuccess=false")) {
                        Log.e(TAG, "getAssetSupplier: 获取供应商失败: " + innerList.get(0).toString());
                        break;
                    }
                    assetSupplierCodeMap.put(innerList.get(0).toString(), innerList.get(1).toString());
                    assetSupplierNameMap.put(innerList.get(0).toString(), innerList.get(2).toString());
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getAssetSupplier: 获取供应商异常", e);
        }
    }

    //计量单位
    public static void getAssetUnit() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        JsonObject data = new JsonObject();
        data.addProperty("FormId", "BD_UNIT");
        data.addProperty("FieldKeys", "FUNITID,FNumber,FName");
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            for (List<Object> innerList : lists) {
                for (int i = 0; i < innerList.size(); i++) {
                    if (innerList.get(0).toString().contains("IsSuccess=false")) {
                        Log.e(TAG, "getAssetUnit: 获取计量单位失败: " + innerList.get(0).toString());
                        break;
                    }
                    assetUnitCodeMap.put(innerList.get(0).toString(), innerList.get(1).toString());
                    assetUnitNameMap.put(innerList.get(0).toString(), innerList.get(2).toString());
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getAssetUnit: 获取计量单位异常", e);
        }
    }

    //资产状态
    public static void getAssetStatus() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        JsonObject data = new JsonObject();
        data.addProperty("FormId", "FA_STATUS");
        data.addProperty("FieldKeys", "FID,FNumber,FName");
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            for (List<Object> innerList : lists) {
                for (int i = 0; i < innerList.size(); i++) {
                    if (innerList.get(0).toString().contains("IsSuccess=false")) {
                        Log.e(TAG, "getAssetStatus: 获取资产状态失败: " + innerList.get(0).toString());
                        break;
                    }

                    assetStatusCodeMap.put(innerList.get(0).toString(), innerList.get(1).toString());
                    assetStatusNameMap.put(innerList.get(0).toString(), innerList.get(2).toString());
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getAssetStatus: 获取资产状态异常", e);
        }
    }

    /**
     * 获取盘点方案（获取已审核）
     * FID,FBillNo,FName,FDOCUMENTSTATUS 内码，编码，方案名称，状态
     *
     * @return
     */
    public static List<KingDeeRepoRet.InventScheme> getInventSchemeNew() {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        K3CloudApi api = new K3CloudApi(identifyInfo);
        String data = "{\"FormId\":\"FA_InventScheme\",\"FieldKeys\":\"FID,FBillNo,FName,FDOCUMENTSTATUS\",\"FilterString\":[{\"Left\":\"(\",\"FieldName\":\"FDOCUMENTSTATUS\",\"Compare\":\"=\",\"Value\":\"C\",\"Right\":\")\",\"Logic\":\"0\"}],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        List<KingDeeRepoRet.InventScheme> inventSchemeList = new ArrayList();
        try {
            //调用接口
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            if (!lists.isEmpty()) {
                for (List<Object> list : lists) {
                    String fId = String.valueOf(list.get(0));
                    KingDeeRepoRet.Invent invent = getInvent(api, fId);
                    if (null != invent) {
                        KingDeeRepoRet.InventScheme inventScheme = new KingDeeRepoRet.InventScheme();
                        inventScheme.setFID(fId);
                        inventScheme.setFBillNo(String.valueOf(list.get(1)));
                        inventScheme.setFName(String.valueOf(list.get(2)));
                        inventScheme.setFDOCUMENTSTATUS(String.valueOf(list.get(3)));
                        inventScheme.setInvent(invent);
                        inventSchemeList.add(inventScheme);
                    }
                }
            }
            Log.i(TAG, "getInventSchemeNew: " + new Gson().toJson(inventSchemeList));
            return inventSchemeList;
        } catch (Exception e) {
            Log.e(TAG, "getInventScheme: 获取盘点方案异常", e);
            return inventSchemeList;
        }
    }

    //获取盘点表为创建状态的方案, key 盘点方案内码 -> 盘点表的编码
    public static KingDeeRepoRet.Invent getInvent(K3CloudApi api, String fId) throws Exception {

//        //已审核的盘点表排除
//        String jsonData = "{\"FormId\":\"FA_CountingReport\",\"FieldKeys\":\"FID,FBillNo,FInventSchemeId,FAssetOrgId,FDOCUMENTSTATUS\"," +
//                "\"FilterString\":[{\"Left\":\"(\",\"FieldName\":\"FInventSchemeId\",\"Compare\":\"=\",\"Value\":\"" + fId + "\",\"Right\":\")\",\"Logic\":\"\"}," +
//                "{\"Left\":\"(\",\"FieldName\":\"FDOCUMENTSTATUS\",\"Compare\":\"=\",\"Value\":\"A\",\"Right\":\")\",\"Logic\":\"0\"}]," +
//                "\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        //已审核的盘点表排除
        String jsonData = "{\"FormId\":\"FA_CountingReport\",\"FieldKeys\":\"FID,FBillNo,FInventSchemeId,FAssetOrgId,FDOCUMENTSTATUS\"," +
                "\"FilterString\":[{\"Left\":\"(\",\"FieldName\":\"FInventSchemeId\",\"Compare\":\"=\",\"Value\":\"" + fId + "\",\"Right\":\")\",\"Logic\":\"\"}]," +
                "\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        List<List<Object>> fBillNoList = api.executeBillQuery(jsonData);
        if (!fBillNoList.isEmpty()) {
            KingDeeRepoRet.Invent invent = new KingDeeRepoRet.Invent();
            invent.setFID(fBillNoList.get(0).get(0).toString());
            invent.setFBillNo(fBillNoList.get(0).get(1).toString());
            invent.setFInventSchemeId(fBillNoList.get(0).get(2).toString());
            invent.setFAssetOrgId(fBillNoList.get(0).get(3).toString());
            invent.setFDOCUMENTSTATUS(fBillNoList.get(0).get(4).toString());
            return invent;
        }
        return null;
    }


    //盘点表内码
    public static List<Asset> getProductListData(String id) {
        List<Asset> assetList = new ArrayList<>();
        try {
            IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
            K3CloudApi api = new K3CloudApi(identifyInfo);
            String jsonData = "{\"CreateOrgId\":,\"Number\":\"\",\"Id\":\"" + id + "\",\"IsSortBySeq\":\"false\"}";
            String formId = "FA_CountingReport";
            //调用接口
            String resultJson = api.view(formId, jsonData);
            //用于记录结果
            Gson gson = new Gson();
            //对返回结果进行解析和校验
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                KingDeeRepoRet kingDeeRepoRet = gson.fromJson(gson.toJson(repoRet.getResult().getResult()), KingDeeRepoRet.class);
                List<KingDeeRepoRet.FA_CountingRptEntry> faCountingRptEntryList = kingDeeRepoRet.getFA_CountingRptEntry();
                for (KingDeeRepoRet.FA_CountingRptEntry faCountingRptEntry : faCountingRptEntryList) {
                    Asset asset = new Asset();
                    //单据状态
                    asset.setfDocumentStatus(kingDeeRepoRet.getDocumentStatus());
                    //型号规格
                    asset.setSpecification(faCountingRptEntry.getSPECIFICATION());
                    //盘点表内码
                    asset.setId(String.valueOf(kingDeeRepoRet.getId()));
                    //盘点表编码
                    asset.setBillNo(String.valueOf(kingDeeRepoRet.getBillNo()));
                    //盘点方案
                    asset.setInventSchemeId(String.valueOf(kingDeeRepoRet.getInventSchemeId_Id()));
                    asset.setInventBillNo(kingDeeRepoRet.getInventSchemeId().getBillNo());
                    //资产卡编码
                    asset.setfNumber(faCountingRptEntry.getCardNumber());

                    //资产类别
                    asset.setfAssetTypeID(String.valueOf(faCountingRptEntry.getAssetTypeId_Id()));
                    KingDeeRepoRet.AssetTypeId assetTypeId = faCountingRptEntry.getAssetTypeId();
                    if (null != assetTypeId) {
                        asset.setfAssetTypeNumber(faCountingRptEntry.getAssetTypeId().getNumber());
                        if (!assetTypeId.getName().isEmpty()) {
                            KingDeeRepoRet.Name name = assetTypeId.getName().get(0);
                            asset.setfAssetTypeName(name.getValue());
                        }
                    }

                    //资产名称
                    if (!faCountingRptEntry.getAssetName().isEmpty()) {
                        KingDeeRepoRet.AssetName assetName = faCountingRptEntry.getAssetName().get(0);
                        asset.setfName(assetName.getValue());
                    }

                    //资产id
                    asset.setfAssetID(String.valueOf(faCountingRptEntry.getAssetId()));
                    //资产编号
                    asset.setfAssetNO(faCountingRptEntry.getAssetNumber());

                    //单位
                    asset.setfUnitID(String.valueOf(faCountingRptEntry.getAssetUnitId_Id()));
                    KingDeeRepoRet.AssetUnitId assetUnitId = faCountingRptEntry.getAssetUnitId();
                    if (null != assetUnitId) {
                        asset.setfUnitNumber(assetUnitId.getNumber().toString());
                        if (!assetUnitId.getName().isEmpty()) {
                            asset.setfUnitName(assetUnitId.getName().get(0).getValue());
                        }
                    }

                    asset.setfAssetOrgID(String.valueOf(new BigDecimal(kingDeeRepoRet.getAssetOrgId_Id()).setScale(0)));
                    if (null != kingDeeRepoRet.getAssetOrgId()) {
                        asset.setfAssetOrgNumber(kingDeeRepoRet.getAssetOrgId().getNumber());
                        if (!kingDeeRepoRet.getAssetOrgId().getName().isEmpty()) {
                            asset.setfAssetOrgName(kingDeeRepoRet.getAssetOrgId().getName().get(0).getValue());
                        }
                    }

                    asset.setfOwnerOrgID(String.valueOf(new BigDecimal(faCountingRptEntry.getOwnerOrgId_Id()).setScale(0)));
                    if (null != faCountingRptEntry.getOwnerOrgId()) {
                        if (!faCountingRptEntry.getOwnerOrgId().getName().isEmpty()) {
                            asset.setfOwnerOrgNumer(faCountingRptEntry.getOwnerOrgId().getNumber());
                            asset.setfOwnerOrgName(faCountingRptEntry.getOwnerOrgId().getName().get(0).getValue());
                        }
                    }
                    //资产位置
                    asset.setfPositionID(String.valueOf(faCountingRptEntry.getBookPositionId_Id()));
                    KingDeeRepoRet.BookPositionId bookPositionId = faCountingRptEntry.getBookPositionId();
                    if (null != bookPositionId) {
                        asset.setfPositionNumber(bookPositionId.getNumber());
                        if (!bookPositionId.getName().isEmpty()) {
                            asset.setfPositionName(bookPositionId.getName().get(0).getValue());
                        }
                    }

                    //账存使用部门
                    asset.setBookUseDeptid(String.valueOf(faCountingRptEntry.getBookUseDeptid_Id()));
                    if (null != faCountingRptEntry.getBookUseDeptid()) {
                        asset.setBookUseDeptNumber(faCountingRptEntry.getBookUseDeptid().getNumber());
                        if (!faCountingRptEntry.getBookUseDeptid().getName().isEmpty()) {
                            asset.setBookUseDeptName(faCountingRptEntry.getBookUseDeptid().getName().get(0).getValue());
                        }
                    }


                    //账存使用人
                    if (null != faCountingRptEntry.getBookUserId_Id()) {
                        asset.setBookUserId_Id(new BigDecimal(faCountingRptEntry.getBookUserId_Id()).setScale(0).toString());
//                        asset.setBookUserNumber(faCountingRptEntry.getBookUserId());

                    }

                    //资产状态
                    asset.setfAssetStatusID(String.valueOf(faCountingRptEntry.getASSETSTATUSID_Id()));
                    if (null != faCountingRptEntry.getAssetStatusId()) {
                        asset.setfAssetStatusNumber(faCountingRptEntry.getAssetStatusId().getNumber());
                        if (!faCountingRptEntry.getAssetStatusId().getName().isEmpty()) {
                            asset.setfAssetStatusName(faCountingRptEntry.getAssetStatusId().getName().get(0).getValue());
                        }
                    }

                    //初盘人
                    String InitCheckerId = String.valueOf(faCountingRptEntry.getInitCheckerId_Id());
                    asset.setInitCheckerId(InitCheckerId);

                    //初盘日期
                    String InitDate = faCountingRptEntry.getInitDate();
                    if (StringUtils.isNotBlank(InitDate)) {
                        LocalDateTime dateTime = LocalDateTime.parse(InitDate);
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        String formattedDate = dateTime.format(formatter);
                        asset.setInitDate(formattedDate);
                    }
                    //初盘资产位置
                    asset.setfPositionID(String.valueOf(faCountingRptEntry.getInitPositionId_Id()));
                    KingDeeRepoRet.InitPositionId initPositionId = faCountingRptEntry.getInitPositionId();
                    if (null != initPositionId) {
                        asset.setfInitPositionNumber(initPositionId.getNumber());
                        if (!initPositionId.getName().isEmpty()) {
                            asset.setfInitPositionName(initPositionId.getName().get(0).getValue());
                        }
                    }

                    //初盘变动使用人
                    String initUserId = String.valueOf(faCountingRptEntry.getInitUserId_Id());
                    asset.setInitUserId(initUserId);
                    if (null != faCountingRptEntry.getInitUserId() && !faCountingRptEntry.getInitUserId().getName().isEmpty()) {
                        asset.setInitUserName(faCountingRptEntry.getInitUserId().getName().get(0).getValue());
                    }

                    //初盘变动使用部门
                    String initUseDeptId = String.valueOf(faCountingRptEntry.getInitUseDeptId_Id());
                    asset.setInitUseDeptId(initUseDeptId);
                    if (null != faCountingRptEntry.getInitUseDeptId()) {
                        asset.setInitUseDeptNumber(faCountingRptEntry.getInitUseDeptId().getNumber());
                        if (!faCountingRptEntry.getInitUseDeptId().getName().isEmpty()) {
                            asset.setInitUseDeptName(faCountingRptEntry.getInitUseDeptId().getName().get(0).getValue());
                        }
                    }

                    //资产数量
                    asset.setfQuantity(String.valueOf(faCountingRptEntry.getBookQty()));
                    //初盘数量
                    if (faCountingRptEntry.getInitQty() != null) {
                        asset.setInitQty(String.valueOf(faCountingRptEntry.getInitQty()));
                    }
                    //盘盈盘亏状态
                    if (StringUtils.isNotBlank(asset.getInitCheckerId())) {
                        asset.setProfitStatus(Long.valueOf(faCountingRptEntry.getProfitStatus()));
                    } else {
                        asset.setProfitStatus(null);
                    }
                    //备注
                    if (!faCountingRptEntry.getEntryDescription().isEmpty()) {
                        asset.setEntryDescription(faCountingRptEntry.getEntryDescription().get(0).getValue());
                    }

                    //是否复盘
                    asset.setReinventory(faCountingRptEntry.getReinventory());
                    //复盘人
                    asset.setReCheckerId(String.valueOf(faCountingRptEntry.getReCheckerId_Id()));
                    if (null != faCountingRptEntry.getReCheckerId()) {
                        asset.setReCheckerName(faCountingRptEntry.getReCheckerId().getName());
                    }
                    //复盘日期
                    String reDate = faCountingRptEntry.getReDate();
                    if (StringUtils.isNotBlank(reDate)) {
                        LocalDateTime dateTime = LocalDateTime.parse(reDate);
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        String formattedDate = dateTime.format(formatter);
                        asset.setReDate(formattedDate);
                    }
                    //复盘使用部门
                    asset.setReUseDeptId(String.valueOf(faCountingRptEntry.getReUseDeptId_Id()));
                    if (null != faCountingRptEntry.getReUseDeptId()) {
                        asset.setReUseDeptNumber(faCountingRptEntry.getReUseDeptId().getNumber());
                        if (!faCountingRptEntry.getReUseDeptId().getName().isEmpty()) {
                            asset.setReUseDeptName(faCountingRptEntry.getReUseDeptId().getName().get(0).getValue());
                        }
                    }
                    //复盘使用人
                    asset.setReUserId(String.valueOf(faCountingRptEntry.getReUserId_Id()));
                    if (null != faCountingRptEntry.getReUserId()) {
                        asset.setReUserNumber(faCountingRptEntry.getReUserId().getStaffNumber());
                        if (!faCountingRptEntry.getReUserId().getName().isEmpty()) {
                            asset.setReUserName(faCountingRptEntry.getReUserId().getName().get(0).getValue());
                        }
                    }

                    //盘点资产位置
                    asset.setRePositionId(String.valueOf(faCountingRptEntry.getRePositionId_Id()));
                    if (null != faCountingRptEntry.getRePositionId()) {
                        asset.setRePositionNumber(faCountingRptEntry.getRePositionId().getNumber());
                        if (!faCountingRptEntry.getRePositionId().getName().isEmpty()) {
                            asset.setRePositionName(faCountingRptEntry.getRePositionId().getName().get(0).getValue());
                        }
                    }
                    //保管人
                    asset.setKeeperId(String.valueOf(faCountingRptEntry.getKEEPERID_Id()));
                    if (null != faCountingRptEntry.getKEEPERID()) {
                        if (!faCountingRptEntry.getKEEPERID().getName().isEmpty()) {
                            asset.setKeeperName(faCountingRptEntry.getKEEPERID().getName().get(0).getValue());
                        }
                    }
                    //todo 个人自盘状态
                    asset.setpStatus(Long.valueOf(faCountingRptEntry.getPSTATUS()));
                    //统计已盘、未盘数量
                    if (StringUtils.isBlank(InitCheckerId)) {
                        asset.setfHasCount("");
                        notCounted++;
                    } else {
                        String status = faCountingRptEntry.getProfitStatus();
                        if (status.equals("0") || status.equals("1") || status.equals("2")) {
                            counted++;
                        } else {
                            errorCounted++;
                        }
                        asset.setfHasCount(faCountingRptEntry.getProfitStatus());
                    }

                    assetList.add(asset);

                }
            }
            return assetList;
        } catch (Exception e) {
            Log.e(TAG, "获取盘点列表异常", e);
            return assetList;
        }

    }


    /**
     * 获取账套信息
     */

    public static void getDataCenters() {
        try {
            IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
            K3CloudApi api = new K3CloudApi(identifyInfo);
            List<DataCenter> datacenters = api.getDataCenters();
            if (null != datacenters && datacenters.size() > 0) {
                for (DataCenter dataCenter : datacenters) {
                    assetDataCenterMap.put(dataCenter.getNumber(), dataCenter.getName());
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取账套异常", e);
        }


    }

    //资产列表
    public static List<Asset> getInventData() {
        try {
            IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
            K3CloudApi api = new K3CloudApi(identifyInfo);
            JsonObject data = new JsonObject();
            data.addProperty("FormId", "FA_CARD");
            data.addProperty("FieldKeys", "FAssetID,FNumber,FAssetStatusID,FAssetTypeID," +
                    "FOwnerOrgID,FAssetOrgID,FQuantity,FUnitID,FDOCUMENTSTATUS,FHASCOUNT,FCOUNTBILLNO,FName,FAssetNO,FPositionID");
            data.addProperty("StartRow", 0);
            data.addProperty("Limit", 10000);
            List<Asset> assetList = new ArrayList<>();
            List<List<Object>> lists = api.executeBillQuery(data.toString());
            if (!lists.isEmpty() && lists.size() > 0) {
                //获取资产类别数据
                getAssetUnit();
                getAssetType();
                getAssetPosition();
                for (List<Object> list : lists) {
                    //只获取已审核的数据
                    if ("C".equals(String.valueOf(list.get(8)))) {
                        Asset asset = new Asset();
                        asset.setfAssetID(String.valueOf(list.get(0)));
                        asset.setfNumber(String.valueOf(list.get(1)));
                        asset.setfAssetStatusID(String.valueOf(list.get(2)));
                        asset.setfAssetTypeID(String.valueOf(list.get(3)));
                        asset.setfAssetTypeName(assetTypeIdAndNameMap.get(String.valueOf(list.get(3))));
                        asset.setfOwnerOrgID(String.valueOf(list.get(4)));
                        asset.setfAssetOrgID(String.valueOf(list.get(5)));
                        asset.setfQuantity(new BigDecimal(String.valueOf(list.get(6))).setScale(0).toString());
                        asset.setfUnitID(String.valueOf(list.get(7)));
                        asset.setfUnitName(assetUnitNameMap.get(String.valueOf(list.get(7))));
                        if ("已审核".equals(String.valueOf(list.get(8)))) {
                            asset.setfDocumentStatus("已审核");
                        }
                        asset.setfHasCount(String.valueOf(list.get(9)));
                        asset.setfCountBillNo(String.valueOf(list.get(10)));
                        asset.setfName(String.valueOf(list.get(11)));
                        asset.setfAssetNO(String.valueOf(list.get(12)));
                        asset.setfPositionID(String.valueOf(list.get(13)));
                        asset.setfPositionName(assetPositionNameMap.get(String.valueOf(list.get(13))));
                        assetList.add(asset);
                    }
                }
            }
            return assetList;
        } catch (Exception e) {
            Log.e(TAG, "getInventData: 接口异常", e);
            return Collections.emptyList();
        }
    }

    public static Boolean uploadData(List<Map<String, Object>> list) {
        Log.i(TAG, "uploadData: " + new Gson().toJson(list));
        try {
            List<Asset> assetList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Gson gson = new Gson();
                String json = gson.toJson(map);
                Asset asset = gson.fromJson(json, Asset.class);
                assetList.add(asset);
            }

            IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
            K3CloudApi api = new K3CloudApi(identifyInfo);
            FaCard faCard = new FaCard();
            faCard.setIgnoreInterationFlag("");
            faCard.setInterationFlags("");
            faCard.setIsAutoAdjustField("false");
            faCard.setIsControlPrecision("false");
            faCard.setIsDeleteEntry("true");
            faCard.setIsEntryBatchFill("true");
            faCard.setIsVerifyBaseDataField("false");
            FaCard.Model model = new FaCard.Model();
            String fAssetOrgNumber = assetList.get(0).getfAssetOrgNumber();
            //todo
            FaCard.Model.FAssetOrgId fAssetOrgId = new FaCard.Model.FAssetOrgId();
            fAssetOrgId.setFNumber(fAssetOrgNumber);
            model.setFAssetOrgId(fAssetOrgId);
            model.setFID(Integer.valueOf(assetList.get(0).getId()).intValue());
            List<FaCard.Model.FEntity> fEntityList = new ArrayList<>();
            for (Asset asset : assetList) {
                //todo
                FaCard.Model.FEntity fEntity = new FaCard.Model.FEntity();
                //资产类别
                FaCard.Model.FEntity.FAssetTypeId fAssetTypeId = new FaCard.Model.FEntity.FAssetTypeId();
                fAssetTypeId.setFNumber(asset.getfAssetTypeNumber());
                fEntity.setFAssetTypeId(fAssetTypeId);

                //单位
                FaCard.Model.FEntity.FAssetUnitId fAssetUnitId = new FaCard.Model.FEntity.FAssetUnitId();
                fAssetUnitId.setFNumber(asset.getfUnitNumber());
                fEntity.setFAssetUnitId(fAssetUnitId);

                //盘点数量
                fEntity.setFBookQty(asset.getfQuantity());
                if (StringUtils.isNotBlank(asset.getInitQty())) {
                    fEntity.setFInitQty(Integer.valueOf(asset.getInitQty()).intValue());
                } else {
                    fEntity.setFInitQty(0);
                }

                int status = new BigDecimal(fEntity.getFBookQty()).compareTo(new BigDecimal(fEntity.getFInitQty()));
                if (status > 0) {
                    //盘亏
                    fEntity.setFProfitStatus("0");
                } else if (status < 0) {
                    //盘亏
                    fEntity.setFProfitStatus("1");
                } else {
                    //无
                    fEntity.setFProfitStatus(null);
                }
                FaCard.Model.FEntity.FOwnerOrgId fOwnerOrgId = new FaCard.Model.FEntity.FOwnerOrgId();
                fAssetOrgId.setFNumber(asset.getfAssetOrgNumber());
                fEntity.setFOwnerOrgId(fOwnerOrgId);

                //资产
                fEntity.setFAssetId(new BigDecimal(asset.getfAssetID()).setScale(0).intValue());
                fEntity.setFAssetName(asset.getfName());
                fEntity.setFAssetNumber(asset.getfAssetNO());
                //型号规格
                fEntity.setfSpecification(asset.getSpecification());


                //帐存部门
                FaCard.Model.FEntity.FBookUseDeptid fBookUseDeptid = new FaCard.Model.FEntity.FBookUseDeptid();
                fBookUseDeptid.setFNumber(asset.getBookUseDeptNumber());
                fEntity.setfBookUseDeptid(fBookUseDeptid);

                //帐存部门
                FaCard.Model.FEntity.FInitUseDeptId fInitUseDeptId = new FaCard.Model.FEntity.FInitUseDeptId();
                fInitUseDeptId.setFNumber(asset.getInitUseDeptNumber());
                fEntity.setFInitUseDeptId(fInitUseDeptId);

                //初盘变动位置
                FaCard.Model.FEntity.FInitPositionId fInitPositionId = new FaCard.Model.FEntity.FInitPositionId();
                fInitPositionId.setFNumber(asset.getfInitPositionNumber());
                fEntity.setFInitPositionId(fInitPositionId);

                //帐存位置
                FaCard.Model.FEntity.FBookPositionId fBookPositionId = new FaCard.Model.FEntity.FBookPositionId();
                fBookPositionId.setFNumber(asset.getfPositionNumber());
                fEntity.setfBookPositionId(fBookPositionId);


                //初盘日期
                fEntity.setInitDate(asset.getInitDate());


                //初盘人
                if (StringUtils.isNotBlank(asset.getInitCheckerId())) {
                    FaCard.Model.FEntity.FInitCheckerId fInitCheckerId = new FaCard.Model.FEntity.FInitCheckerId();
                    fInitCheckerId.setFUserID(asset.getInitCheckerId());
                    fEntity.setfInitCheckerId(fInitCheckerId);
                }
                //初盘使用人
                if (StringUtils.isNotBlank(asset.getInitUserId())) {
                    FaCard.Model.FEntity.FInitUserId fInitUserId = new FaCard.Model.FEntity.FInitUserId();
                    fInitUserId.setFStaffNumber(asset.getInitUserNumber());
                    fEntity.setfInitUserId(fInitUserId);
                }

                //保管人
                if (StringUtils.isNotBlank(asset.getKeeperId())) {
                    FaCard.Model.FEntity.FKeeperId fKeeperId = new FaCard.Model.FEntity.FKeeperId();
                    fKeeperId.setFSTAFFNUMBER(asset.getKeeperId());
                    fEntity.setfKeeperId(fKeeperId);
                }
                //是否复盘
                fEntity.setfIsReinventory(String.valueOf(asset.getReinventory()));

                if (StringUtils.isNotBlank(asset.getRePositionId())) {
                    FaCard.Model.FEntity.FRePositionId fRePositionId = new FaCard.Model.FEntity.FRePositionId();
                    fRePositionId.setFNumber(asset.getRePositionNumber());
                    fEntity.setfRePositionId(fRePositionId);
                }

                if (StringUtils.isNotBlank(asset.getReUseDeptId())) {
                    FaCard.Model.FEntity.FReUseDeptId fReUseDeptId = new FaCard.Model.FEntity.FReUseDeptId();
                    fReUseDeptId.setFNumber(asset.getReUseDeptNumber());
                    fEntity.setFReUseDeptId(fReUseDeptId);
                }

                if (StringUtils.isNotBlank(asset.getReUserId())) {
                    FaCard.Model.FEntity.FReUserId fReUserId = new FaCard.Model.FEntity.FReUserId();
                    fReUserId.setFStaffNumber(asset.getReUserNumber());
                    fEntity.setFReUserId(fReUserId);
                }

                if (StringUtils.isNotBlank(asset.getReCheckerId())) {
                    FaCard.Model.FEntity.FReCheckerId reCheckerId = new FaCard.Model.FEntity.FReCheckerId();
                    reCheckerId.setFUserID(asset.getReCheckerId());
                    fEntity.setFReCheckerId(reCheckerId);
                }

                //复盘日期
                String reDate = asset.getReDate();
                fEntity.setFReDate(asset.getReDate());


                //资产状态
                FaCard.Model.FEntity.FASSETSTATUSID fassetStatusId = new FaCard.Model.FEntity.FASSETSTATUSID();
                fassetStatusId.setFNumber(asset.getfAssetStatusNumber());
                fEntity.setASSETSTATUSID(fassetStatusId);

                fEntity.setFCardNumber(asset.getfNumber());

                fEntityList.add(fEntity);
            }
            model.setFEntity(fEntityList);
            //盘点方案id
            FaCard.Model.FInventSchemeId fInventSchemeId = new FaCard.Model.FInventSchemeId();
            fInventSchemeId.setFBILLNO(assetList.get(0).getInventBillNo());
            model.setFInventSchemeId(fInventSchemeId);

            faCard.setModel(model);
            List<String> needUpDateFields = new ArrayList<>();
            faCard.setNeedReturnFields(new ArrayList<>());
            faCard.setNeedUpDateFields(needUpDateFields);
            faCard.setNumberSearch("true");
            faCard.setSubSystemId("");
            faCard.setValidateFlag("true");
            faCard.setValidateRepeatJson("false");
            String formId = "FA_CountingReport";
            //调用接口
            Log.i(TAG, "uploadData request: " + new Gson().toJson(faCard));
            String resultJson = api.save(formId, new Gson().toJson(faCard));
            Gson gson = new Gson();
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                //提交操作
                JsonObject sumbitData = new JsonObject();
                JsonArray sumbitArray = new JsonArray();
                sumbitArray.add(assetList.get(0).getBillNo());
                sumbitData.add("Numbers", sumbitArray);
                String submitStr = api.submit("FA_CountingReport", new Gson().toJson(sumbitData));
                RepoRet repoRetSubmit = gson.fromJson(submitStr, RepoRet.class);
                if (repoRetSubmit.getResult().getResponseStatus().isIsSuccess()) {
                    //审核
                    JsonObject auditData = new JsonObject();
                    JsonArray auditArray = new JsonArray();
                    auditArray.add(assetList.get(0).getBillNo());
                    auditData.add("Numbers", auditArray);
                    String auditStr = api.audit("FA_CountingReport", new Gson().toJson(auditData));
                    RepoRet auditRepoRet = gson.fromJson(auditStr, RepoRet.class);
                    if (auditRepoRet.getResult().getResponseStatus().isIsSuccess()) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "uploadData: 异常" + e);
            return false;
        }
        return false;
    }

    public static String submitAsset(String assetNo, String assetName, String quantity, String unit,
                                     String position, String type, String policy, String orgCost,
                                     String acctDate, String useDept, String allocCostItem, String status) {
        String fassetOrgNumber = "0";
        String fAssetStatusNumber = status;//"ZCZT01_SYS";
        String fAssetTypeNumber = type; //"ZCLB01_SYS";
        String funitID = unit; //"cm";
        String fAssetNo = assetNo; // "SH00001";
        String fPositionNumber = position;//"ZCWZ0001";
        String quanitiy = quantity;//"1";
        String fName = assetName;//"测试资产111";
        //会计政策
        String fFinanceId = "";
        String fAcctDate = acctDate;//"2024-09-10";
        Long fOriginalCost = Long.valueOf(orgCost); //10L; //未税成本
        String fAcctPolicyNumber = policy;//"KJZC01_SYS";
        //资产编码相关
        String fallocAssetNo = assetNo; //"SH00001";
        //使用分配 部分
        String fAllocUseDeptNumber = useDept; //"BM000002";
        String fAllocCostItemNumber = allocCostItem;// "FYXM02_SYS";


        try {
            AddAsset asset = new AddAsset();
            asset.setIgnoreInterationFlag("");
            asset.setInterationFlags("");
            asset.setIsAutoAdjustField("false");
            asset.setIsControlPrecision("false");
            asset.setIsDeleteEntry("true");
            asset.setIsEntryBatchFill("true");
            asset.setIsVerifyBaseDataField("false");
            AddAsset.Model model = new AddAsset.Model();
            //资产数据
            AddAsset.Model.FAssetOrgID fAssetOrgID = new AddAsset.Model.FAssetOrgID();
            fAssetOrgID.setFNumber(fassetOrgNumber);
            model.setFAssetOrgID(fAssetOrgID);

            AddAsset.Model.FAssetStatusID fAssetStatusID = new AddAsset.Model.FAssetStatusID();
            fAssetStatusID.setFNumber(fAssetStatusNumber);
            model.setFAssetStatusID(fAssetStatusID);

            AddAsset.Model.FAssetTypeID fAssetTypeID = new AddAsset.Model.FAssetTypeID();
            fAssetTypeID.setFNumber(fAssetTypeNumber);
            model.setFAssetTypeID(fAssetTypeID);

            AddAsset.Model.FUnitID fUnitID = new AddAsset.Model.FUnitID();
            fUnitID.setFNumber(funitID);
            model.setFUnitID(fUnitID);
            List<AddAsset.Model.FCardDetail> fCardDetailList = new ArrayList<>();
            AddAsset.Model.FCardDetail fCardDetail = new AddAsset.Model.FCardDetail();
            fCardDetail.setFID(null);
            fCardDetail.setFAssetNO(fAssetNo);
            AddAsset.Model.FCardDetail.FPositionID fPositionID = new AddAsset.Model.FCardDetail.FPositionID();
            fPositionID.setFNumber(fPositionNumber);
            fCardDetail.setFPositionID(fPositionID);
            fCardDetail.setFDetailQuantity("1");
            fCardDetailList.add(fCardDetail);
            model.setFCardDetail(fCardDetailList);
            model.setFName(fName);


            //会计政策
            List<AddAsset.Model.FFinance> fFinanceList = new ArrayList<>();
            AddAsset.Model.FFinance fFinance = new AddAsset.Model.FFinance();
            fFinance.setFFinanceID(fFinanceId);
            fFinance.setFAcctDate(fAcctDate);
            fFinance.setFOriginalCost(fOriginalCost);
            AddAsset.Model.FFinance.FAcctPolicyID fAcctPolicyID = new AddAsset.Model.FFinance.FAcctPolicyID();
            fAcctPolicyID.setFNumber(fAcctPolicyNumber);
            fFinance.setFAcctPolicyID(fAcctPolicyID);
            fFinanceList.add(fFinance);
            model.setFFinanceList(fFinanceList);

            //资产编码
            List<AddAsset.Model.FAllocation> fAllocationList = new ArrayList<>();
            AddAsset.Model.FAllocation fAllocation = new AddAsset.Model.FAllocation();
            fAllocation.setFID("");
            fAllocation.setFAllocAssetNO(fallocAssetNo);
            AddAsset.Model.FAllocation.FAllocUseDeptID fAllocUseDeptID = new AddAsset.Model.FAllocation.FAllocUseDeptID();
            fAllocUseDeptID.setFNumber(fAllocUseDeptNumber);
            fAllocation.setFAllocUseDeptID(fAllocUseDeptID);
            AddAsset.Model.FAllocation.FAllocCostItemID fAllocCostItemID = new AddAsset.Model.FAllocation.FAllocCostItemID();
            fAllocCostItemID.setFNumber(fAllocCostItemNumber);
            fAllocation.setFAllocCostItemID(fAllocCostItemID);
            fAllocationList.add(fAllocation);
            model.setFAllocationList(fAllocationList);


            asset.setModel(model);
            asset.setNeedReturnFields(Collections.emptyList());
            asset.setNeedUpDateFields(Collections.emptyList());
            asset.setNumberSearch("true");
            asset.setSubSystemId("");
            asset.setValidateFlag("true");
            asset.setValidateRepeatJson("false");

            IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
            K3CloudApi api = new K3CloudApi(identifyInfo);


            String resultJson = api.save("FA_CARD", new Gson().toJson(asset));
            Gson gson = new Gson();
            RepoRet repoRet = gson.fromJson(resultJson, RepoRet.class);
            if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
                Long id = Long.valueOf(repoRet.getResult().getId());
                //提交操作
                JsonObject sumbitData = new JsonObject();
                sumbitData.addProperty("Ids", id);
                String submitStr = api.submit("FA_CARD", new Gson().toJson(sumbitData));
                RepoRet repoRetSubmit = gson.fromJson(submitStr, RepoRet.class);
                if (repoRetSubmit.getResult().getResponseStatus().isIsSuccess()) {
                    //审核
                    JsonObject auditData = new JsonObject();
                    auditData.addProperty("Ids", id);
                    String auditStr = api.audit("FA_CARD", new Gson().toJson(auditData));
                    RepoRet auditRepoRet = gson.fromJson(auditStr, RepoRet.class);
                    if (auditRepoRet.getResult().getResponseStatus().isIsSuccess()) {
                        return "1";
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "submitAsset: 异常", e);
            return null;
        }
        return null;
    }


}
